from django.contrib.auth.hashers import make_password, check_password
from rest_framework.response import Response
from rest_framework.views import APIView
import re
from django.db.models import Q


from myapp.models import User

#注册接口
class RegisterView(APIView):
    def get(self, request):
        '''
        用户注册接口
        :param request: 接受到的数据
        :return: 返回响应
        '''
        # 接收参数
        username = request.GET.get('username', None)
        password = request.GET.get('password', None)

        # 排重操作
        user = User.objects.filter(username=username).first()

        if user:
            return Response({'code': 403, 'msg': '用户名已存在'})

        # 入库
        user = User(username=username, password=make_password(password))

        # 保存结果
        user.save()

        return Response({'code': 200, 'msg': '注册成功'})

    def post(self, request):
        '''
        用户注册接口
        :param request: 接受到的数据
        :return: 返回响应
        '''
        # 接收参数
        print(request.POST)
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        phone = request.POST.get('phone')
        print('username',username)
        print('password',password)
        print('phone',phone)
        check_phone = "^1[3456789]\d{9}$"
        if not re.match(check_phone,str(phone)):
            return Response({'code': 1001, 'msg': '手机号不合法'})

        # 排重操作
        user = User.objects.filter(username=username).first()

        if user:
            return Response({'code': 403, 'msg': '用户名已存在'})

        # 入库
        user = User(username=username, password=make_password(password), phone=phone)

        # 保存结果
        user.save()

        return Response({'code': 200, 'msg': '注册成功'})

# 登录接口
class LoginView(APIView):

    def post(self, request):
        '''
        多账号登录接口
        :param request: 获取传进来的账号，密码
        :return: 返回响应信息
        '''
        username = request.data.get('username')
        password = request.data.get('password')
        phone = int(request.data.get('phone'))
        user = User.objects.filter(username=username).first()
        password1 = check_password(password,user.password)
        # 校验正账号密码是否一致,且多账号登录
        userlogin = User.objects.filter(username=username,phone=phone).first()
        if not userlogin and not password1:
            return Response({"code":1001,'msg':'用户名或密码错误'})
        return Response({"code":200,'msg':'登录成功','data':{'uid':userlogin.id,'username':userlogin.username}})


class make_code(APIView):
    def post(self,request):
        '''
        验证码接口
        :param request: 发送的验证码
        :return: 返回的验证码
        :todo 制作验证码
        '''
        pass
